package com.longge;

import java.util.HashMap;
import java.util.Map;

public class CountCompleteSubstring {

    public int countCompleteSubstrings(String word, int k) {
        Map<Character, Integer> countMap = new HashMap<>();
        int n = word.length();
        int result = 0;

        // 统计每个字符出现的次数
        for (int i = 0; i < n; i++) {
            char c = word.charAt(i);
            countMap.put(c, countMap.getOrDefault(c, 0) + 1);
        }

        // 移动窗口并检查字符是否满足条件
        for (int i = 0; i <= n - k; i++) {
            Map<Character, Integer> windowCountMap = new HashMap<>(countMap);
            boolean isValid = true;

            // 移动左指针，更新窗口中的字符计数
            for (int j = i; j < i + k; j++) {
                char c = word.charAt(j);
                windowCountMap.put(c, windowCountMap.get(c) - 1);
                if (windowCountMap.get(c) < 0) {
                    isValid = false;
                    break;
                }
            }

            // 检查相邻字符是否满足条件
            if (isValid) {
                for (int j = 0; j < k - 1; j++) {
                    char c = word.charAt(i + j);
                    char nextChar = word.charAt(i + j + 1);
                    if (Math.abs(c - nextChar) > 2) {
                        isValid = false;
                        break;
                    }
                }
            }

            if (isValid) {
                result++;
            }
        }

        return result;
    }
}
